# coding:utf-8
"""
@author: jing
@contact: 529548204@qq.com
@file: encryption.py
@time: 2022/5/17 14:22
"""
import hashlib

from functools import wraps

from config.confManage import encryption_manage
from util.tools.randomData import replace_random


class Encryption(object):

    def __init__(self, api_key=encryption_manage("${sign}$")):
        self.api_key = api_key
        self.data = {}

    def __call__(self, func):
        @wraps(func)
        def wrapped_function(*args, **kwargs):
            # 处理pytest数据驱动的加密数据

            self.data = eval(replace_random(kwargs["casedata"]["data"]))
            kwargs["casedata"]["data"]["param"] = self.custom_encryption()
            # kwargs["casedata"]["data"]["param"] = self.data["param"]
            return func(*args, **kwargs)

        return wrapped_function

    def custom_encryption(self):
        """
        自定义加密规则 (规则需要自己写以下为例子)
        返回结果是加密后全部参数 可以是"a=1&b=2"也可以是{"a":1,"b":2}
        :return:
        """
        if "sign" in self.data["param"]:
            # 弹出sign
            self.data["param"].pop('sign')
        data_list = []
        for key in sorted(self.data["param"]):
            if self.data["param"][key]:
                data_list.append("%s=%s" % (key, self.data["param"][key]))
        lastdata = "&".join(data_list)
        data = lastdata + "&key=" + self.api_key.strip()
        md = hashlib.md5()
        md.update(data.encode("utf-8"))
        signature = md.hexdigest().upper()
        self.data["param"]['sign'] = signature
        dictxml = self.data["param"]
        # dict转成xml
        return dictxml


if __name__ == '__main__':
    api_keys = "8ViypSUsKSbK26g7HDsKtZSCTUsTtEvB"
    da = {"data": {
        "param": {'mch_id': "$RandomInt(1,2)$", 'nonce_str': 'eh0k52jvvvs51dbxr2pd', 'out_trade_no': 10002112123231,
                  'sign': '{{sign}}'}}}
    # da = {"data": {"param":"a=1&b=$RandomPosInt(1,333)$"}}


    @Encryption()
    def mytest(casedata):
        print(casedata)


    mytest(casedata=da)
    # s = logit(api_keys,da)
    # s.send_post()

    # s.data_processing()
    # s.md5()
    # print(s.rewrite_xml())
    # s.rewrite_xml()
